
import { computed, ref, reactive } from 'vue';
import store from '@/store';
import { PollTask } from '@/lib/tools';
import dayjs from 'dayjs';


export default function useReport() {
   /** --------------心跳 start -------------- */

   const report = ref();

   const watchState = reactive({
        startTime: 0, // 开始播放时间
        watchTime: 0, // 每次发心跳看课时长
        isStop: false, // 是否暂停
   });


    // 全部备案信息
    const publishBrand = computed(() => {
        return store.state.brand?.publishBrand || {};
    })

    // 获取当前用户信息
    const currentUser = computed(() => {
        return store.state?.currentUser || {};
    })

    // 状态
    const actionState = ref('online');


    let poll = null;

    // 发心跳异常次数
    const reportFnTime = ref(0);

    // 发送心跳间隔时间
    const reportIntervalTime = ref(0);

    // 根据心跳配置发送心跳数据
    async function reportFn(moocId, courseWareId, watchLocation = 0, onlineState = '') {
        report.value = {moocId, courseWareId, watchLocation};
        reportFnTime.value ++;
        actionState.value = onlineState || actionState.value;
        return G_transmit('hbPolicy', {message: false}).then(async(res) => {
            reportIntervalTime.value = res.data.interval;
            if(reportIntervalTime.value) {
                try {
                    poll = new PollTask();
                    await poll.startPoll(hbReport, validateCode, reportIntervalTime.value * 1000);
                }catch (error) {
                    reportErrorEvent();
                }
            }
        }).catch((_err) => {
            reportErrorEvent();
            console.log(_err)
        })
    }

    // 结束心跳
    function endReportFn() {
        poll && poll.abortPoll();
    }

    /**
     * policy 请求失败
     * a) 尝试3次请求policy（每次间隔 5 秒），<=3 次以内成功，正常发心跳
     * b) 尝试3次请求policy（每次间隔 5 秒），>3 不在尝请求使用默认心跳间隔发送心跳（默认间隔为25），正常发心跳
     */
    async function reportErrorEvent() {
        if(reportFnTime.value < 3) {
            setTimeout(() => {
                reportFn();
            }, 5000);   
        } else {
            reportIntervalTime.value = 25 * 1000;
            if(!poll) {
                poll = new PollTask();
            }
            await poll.startPoll(hbReport, validateCode, reportIntervalTime.value);
        }
    }

    function validateCode(result) {
        return false;
    }

    // 上报心跳
    /**
     * 
     * @param {*} watchLocation 
     * @param {*} onlineState action类型 online|offline ，文档类型初始化传offline
     * @param {*} initReportType 发心跳类型, 文档类型初始化时发一次offline的心跳，优化延迟
     * @param {*} reportObj 初始化发心跳必要参数
     * @returns 
     */
    async function hbReport(watchLocation = 0, /*onlineState = '', initReportType = '', reportObj = {}*/) {
        if(watchState.startTime === 0) { // 初始化的时候不发心跳
            return;
        }
        if(!watchState.isStop) { // 如果没有暂停，重新计算时长
            watchState.watchTime = dayjs().unix() - watchState.startTime;
        }
        if(watchState.watchTime > reportIntervalTime.value + 35) { // 如果改成未来的系统时间，则不能超过上报机制时长
            watchState.watchTime = reportIntervalTime.value + 35;
        }
        // console.log('上报时长目录', report.value.courseWareId);
        // if(actionState.value === 'offline') {
        //     console.log('暂停上报时长====',  watchState.watchTime);
        // }else {
        //     console.log('上报时长====',  watchState.watchTime);
        // }
        if(watchState.watchTime <= 0) { // 往前修改系统时间或者看课时长为0 都不计算时长
            return;
        }
        if(!report.value?.moocId || !report.value?.courseWareId) {
            return;
        }
        let params = {
            appId: 100002,
            bizId: report.value.moocId,
            bizType: 'mooc',
            dataType: 'pull2',
            device: window.navigator.userAgent,
            resId: report.value.courseWareId,
            resSource: 'courseWare',
            resType: 'rec',
            userClient: 'PC-DEFAULT',
            watchTime: watchState.watchTime,
            dtBrand: publishBrand.value.brand,
            dtTenant: publishBrand.value.brandTenant.tenant,
            packageName: 'ruiyun2-mooc-web',
            bizUserId: currentUser.value.userId,
            realName: currentUser.value.name,
            headImage: currentUser.value.icon
        }
        
       if(actionState.value) {
            params.action = actionState.value;
        }
        let watchLocation1 = watchLocation || report.value.watchLocation;
        if(watchLocation1>= 0) { // 观看位置
            params.watchLocation = watchLocation1;
        }
        let res = {};
        try {
            res = await G_transmit('hbReport', {
                data: params,
                message: false
            })
            watchState.watchTime = 0;
            watchState.startTime = dayjs().unix();
            actionState.value = 'online';
        }catch(err){
             console.log('err', err);
        }
        return res;
    }

    // 开始计算看课时间
    function startWatchTime() {
        watchState.startTime = dayjs().unix();
        watchState.isStop = false;
        // console.log('准备开始计时====', watchState.startTime);
        // console.log('准备开始计时时长====', watchState.watchTime);
    }

    // 开始计算看课时间
    function endWatchTime() { // 暂停之后上报心跳，上报结束后，watchTime = 0；如果不再点击play，就不会再发心跳
        // console.log('暂停或者结束====', dayjs().unix());
        watchState.watchTime = dayjs().unix() - watchState.startTime;
        watchState.startTime = dayjs().unix();
        watchState.isStop = true;
        actionState.value = 'offline'
    }

    return{
        reportFn, startWatchTime, endWatchTime, endReportFn, hbReport
    }
}
